﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Services;
using System.Web.UI.WebControls;
using BLL;
using Model;
using Util;

namespace GeniusWebApplication
{
    public partial class upload : System.Web.UI.Page
    {
        public User user = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            user = (User)HttpContext.Current.Session["user"];
            if (user == null)
                Response.Redirect("log.aspx");
            initDropDown();

            bt_upload.Attributes.Add("onclick", "return checkFileType();");


            //初始化关键字
            IList<Keyword> kl = new KeywordService().getKeywords();
            List<string> keyStringList = new List<string>();
            List<int> keyStringListBig = new List<int>();
            foreach (Keyword k in kl)
            {

                if (keyStringList.Count() == 0)
                {
                    keyStringList.Add(k.keywordName);
                    keyStringListBig.Add(5);
                }
                else if (keyStringList.FindIndex(delegate(string s) { return s == k.keywordName; }) == -1)
                {
                    keyStringList.Add(k.keywordName);
                    keyStringListBig.Add(5);
                }
                else
                {
                    int ii = keyStringList.FindIndex(delegate(string s) { return s == k.keywordName; });
                    if (keyStringListBig[ii] >= 2)
                    {
                        keyStringListBig[ii] = keyStringListBig[ii] - 1;
                    }
                }
            }

            for (int m = 0; m < keyStringList.Count(); m++)
            {
                this.keys.InnerHtml = this.keys.InnerHtml + "<div class='keysItem'><p class='ggz" + keyStringListBig[m] + "'><a href='./keywords.aspx?keys=" + keyStringList[m] + "'>" + keyStringList[m] + "</a></p></div>";
            }

            //初始化我的上传资源
            //<div> 聊斋志异·1</div>
            IList<Resource> relist = new ResourceService().getResourceByUser(user);
            foreach (Resource r in relist)
            {
                if (r.status == 1)
                {
                    if (r.type == 1)
                    {
                        this.con.InnerHtml = this.con.InnerHtml + "<div><a href='./item_media.aspx?resourceId=" + r.id + "'>" + r.resourceName + "</a></div>";
                    }
                    else if (r.type == 2)
                    {
                        this.con.InnerHtml = this.con.InnerHtml + "<div><a href='./item.aspx?resourceId=" + r.id + "'>" + r.resourceName + "</a></div>";
                    }
                    else if (r.type == 3)
                    {
                        this.con.InnerHtml = this.con.InnerHtml + "<div><a href='./item_else.aspx?resourceId=" + r.id + "'>" + r.resourceName + "</a></div>";
                    }
                }
                else
                {

                    this.con.InnerHtml = this.con.InnerHtml + "<div>" + r.resourceName + "</div>";

                }
            }


        }

        private void initDropDown()
        {
            //初始化资源类型下拉框
            IList<Category> cl = new CategoryService().getCategoryList();
            int i = 0;
            foreach (Category c in cl)
            {
                dd_resourceType.Items.Add(new ListItem(c.chineseName, ("" + c.id)));
                i++;
            }
            //初始化部门下拉框
            IList<Department> dl = new DepartmentService().getDepartmentList();
            i = 1;
            dd_department.Items.Add(new ListItem("所有部门", "0"));
            foreach (Department d in dl)
            {
                dd_department.Items.Add(new ListItem(d.name, ("" + d.id)));
                i++;
            }
        }

        public void ButtonUpload_Click(object sender, EventArgs e)
        {
            string bigFileName = hf_resourceFileName.Value;
            if (bigFileName == "") //不是大文件
            {
                if (!FileUpload1.HasFile)
                {
                    Response.Write("<script>alert('请上传文件');</script>");
                    return;
                }

                string resourceName = t_resourceName.Text;
                int categoryId = int.Parse(dd_resourceType.SelectedItem.Value);
                string keywords = t_keywords.Text;
                string filename = FileUpload1.FileName;
                string description = t_resourceDescription.Text;
                int departmentId = int.Parse(dd_department.SelectedItem.Value);

                ResourceService rs = new ResourceService();
                //0 判断类型
                int type = FileUtil.getResourceType(filename);
                //保存路径
                ////1 根据类型保存文件 使用GUID
                string dir = "";
                if (type == 1) //flv文件
                {
                    dir = Server.MapPath("~/uploaded/media/");
                    string path = dir + FileUtil.renameFile(filename, CommonUtil.getGUID());
                    FileUpload1.PostedFile.SaveAs(path);
                    Hashtable ht = rs.uploadResource(
                                        resourceName,
                                        user,
                                        categoryId,
                                        keywords,
                                        filename,
                                        path,
                                        "", /* flv不转换 */
                                        description,
                                        departmentId,
                                        1
                                       );
                    if ((string)ht["result"] == "0")
                    {
                        //上传失败
                        string message = (string)ht["message"];
                        Response.Write("<script>alert('" + message + "');</script>");
                    }
                    else
                    {
                        //上传成功
                        new UserService().addResource(user, (Resource)ht["resource"]);
                        string message = (string)ht["message"];
                        Response.Write("<script>alert('" + message + "');</script>");
                        Response.Write("<script>window.location.href='self.aspx';</script>");
                    }
                }
                if (type == 3) //其他文件
                {
                    dir = Server.MapPath("~/uploaded/docs/source/");
                    string path = dir + FileUtil.renameFile(filename, CommonUtil.getGUID());
                    FileUpload1.PostedFile.SaveAs(path);
                    Hashtable ht = rs.uploadResource(
                                        resourceName,
                                        user,
                                        categoryId,
                                        keywords,
                                        filename,
                                        path,
                                        "",
                                        description,
                                        departmentId,
                                        3
                                       );
                    if ((string)ht["result"] == "0")
                    {
                        //上传失败
                        string message = (string)ht["message"];
                        Response.Write("<script>alert('" + message + "');</script>");
                    }
                    else
                    {
                        //上传成功
                        new UserService().addResource(user, (Resource)ht["resource"]);
                        string message = (string)ht["message"];
                        Response.Write("<script>alert('" + message + "');</script>");
                        Response.Write("<script>window.location.href='self.aspx';</script>");
                    }
                    return;
                }

                if (type == 2) //转换+建立索引
                {
                    string extension = FileUtil.getFileExtension(filename);
                    switch (extension)
                    {
                        case ".doc":
                            dir = Server.MapPath("~/uploaded/docs/");
                            //原始文件
                            string newName = FileUtil.renameFile(filename, CommonUtil.getGUID());
                            newName = newName.Replace(" ", "");
                            string path = dir + "source/" + newName;
                            FileUpload1.SaveAs(path);
                            //开始转换
                            string transformPath = dir + "transform/" + newName;

                            string flashPath = dir + "transform/" + CommonUtil.getGUID() + ".swf";

                            //保存文档
                            Hashtable ht = rs.uploadResource(
                                        resourceName,
                                        user,
                                        categoryId,
                                        keywords,
                                        filename,
                                        path,
                                        flashPath, //转换后的路径 
                                        description,
                                        departmentId,
                                        2
                                       );
                            if ((string)ht["result"] == "0")
                            {
                                //上传失败
                                string message = (string)ht["message"];
                                Response.Write("<script>alert('" + message + "');</script>");
                            }
                            else
                            {
                                //上传成功
                                Resource resource = (Resource)ht["resource"];
                                new UserService().addResource(user, resource);

                                TransformThread myThread = new TransformThread(resource, transformPath);
                                Thread thread = new Thread(myThread.beginTransformWord);
                                thread.Start();
                                Response.Write("<script>alert('上传成功');</script>");
                                Response.Write("<script>window.location.href='self.aspx';</script>");
                                return;
                            }

                            break;
                        case ".pdf":
                            dir = Server.MapPath("~/uploaded/docs/");
                            //原始文件
                            newName = FileUtil.renameFile(filename, CommonUtil.getGUID());
                            path = dir + "source/" + newName;
                            FileUpload1.SaveAs(path);
                            //开始转换
                            transformPath = dir + "transform/" + newName;

                            flashPath = dir + "transform/" + CommonUtil.getGUID() + ".swf";

                            //保存文档
                            ht = rs.uploadResource(
                                        resourceName,
                                        user,
                                        categoryId,
                                        keywords,
                                        filename,
                                        path,
                                        flashPath, //转换后的路径 
                                        description,
                                        departmentId,
                                        2
                                       );
                            if ((string)ht["result"] == "0")
                            {
                                string message = (string)ht["message"];
                                Response.Write("<script>alert('" + message + "');</script>");
                            }
                            else
                            {
                                //上传成功
                                Resource resource = (Resource)ht["resource"];
                                new UserService().addResource(user, resource);

                                TransformThread myThread = new TransformThread(resource, transformPath);
                                Thread thread = new Thread(myThread.beginTransformPdf);
                                thread.Start();
                                Response.Write("<script>alert('上传成功');</script>");
                                Response.Write("<script>window.location.href='self.aspx';</script>");
                                return;
                            }
                            break;
                        default:
                            break;
                    }
                    return;
                }
            }
            else
            {
                //开始处理大文件
                string resourceName = t_resourceName.Text;
                int categoryId = int.Parse(dd_resourceType.SelectedItem.Value);
                string keywords = t_keywords.Text;
                string description = t_resourceDescription.Text;
                int departmentId = int.Parse(dd_department.SelectedItem.Value);

                ResourceService rs = new ResourceService();
                //0 判断类型
                int type = FileUtil.getResourceType(bigFileName);
                string dir = "";
                string bigFileDir = "";
                if (type == 1) //flv文件
                {
                    dir = Server.MapPath("~/uploaded/media/");
                    bigFileDir = dir + bigFileName;
                    string path = dir + FileUtil.renameFile("media.flv", CommonUtil.getGUID());
                    //重命名文件
                    File.Move(bigFileDir, path);
                    Hashtable ht = rs.uploadResource(
                                        resourceName,
                                        user,
                                        categoryId,
                                        keywords,
                                        bigFileName,
                                        path,
                                        "", /* flv不转换 */
                                        description,
                                        departmentId,
                                        1
                                       );
                    if ((string)ht["result"] == "0")
                    {
                        //上传失败
                        string message = (string)ht["message"];
                        Response.Write("<script>alert('" + message + "');</script>");
                    }
                    else
                    {
                        //上传成功
                        new UserService().addResource(user, (Resource)ht["resource"]);
                        string message = (string)ht["message"];
                        Response.Write("<script>alert('上传成功');</script>");
                        Response.Write("<script>window.location.href='self.aspx';</script>");
                    }
                    return;
                }
                if (type == 2) //转换+建立索引
                {
                    string extension = FileUtil.getFileExtension(bigFileName);
                    switch (extension)
                    {
                        case ".doc":
                            //原始文件
                            dir = Server.MapPath("~/uploaded/");
                            bigFileDir = dir + "media/" + bigFileName;
                            string newName = FileUtil.renameFile("media.doc", CommonUtil.getGUID());
                            string path = dir + "docs/source/" + newName;
                            //重命名文件
                            File.Move(bigFileDir, path);
                            //开始转换
                            string transformPath = dir + "docs/transform/" + newName;

                            string flashPath = dir + "docs/transform/" + CommonUtil.getGUID() + ".swf";

                            //保存文档
                            Hashtable ht = rs.uploadResource(
                                        resourceName,
                                        user,
                                        categoryId,
                                        keywords,
                                        bigFileName,
                                        path,
                                        flashPath, //转换后的路径 
                                        description,
                                        departmentId,
                                        2
                                       );
                            if ((string)ht["result"] == "0")
                            {
                                //上传失败
                                string message = (string)ht["message"];
                                Response.Write("<script>alert('" + message + "');</script>");
                            }
                            else
                            {
                                //上传成功
                                Resource resource = (Resource)ht["resource"];
                                new UserService().addResource(user, resource);

                                TransformThread myThread = new TransformThread(resource, transformPath);
                                Thread thread = new Thread(myThread.beginTransformWord);
                                thread.Start();
                                Response.Write("<script>alert('上传成功');</script>");
                                Response.Write("<script>window.location.href='self.aspx';</script>");
                                return;
                            }
                            break;
                        case ".pdf":
                            dir = Server.MapPath("~/uploaded/");
                            bigFileDir = dir + "media/" + bigFileName;
                            newName = FileUtil.renameFile(bigFileName, CommonUtil.getGUID());
                            path = dir + "docs/source/" + newName;
                            //重命名文件
                            File.Move(bigFileDir, path);

                            //开始转换
                            transformPath = dir + "docs/transform/" + newName;

                            flashPath = dir + "docs/transform/" + CommonUtil.getGUID() + ".swf";

                            //保存文档
                            ht = rs.uploadResource(
                                        resourceName,
                                        user,
                                        categoryId,
                                        keywords,
                                        bigFileName,
                                        path,
                                        flashPath, //转换后的路径 
                                        description,
                                        departmentId,
                                        2
                                       );
                            if ((string)ht["result"] == "0")
                            {
                                //上传失败
                                string message = (string)ht["message"];
                                Response.Write("<script>alert('" + message + "');</script>");
                            }
                            else
                            {
                                //上传成功
                                Resource resource = (Resource)ht["resource"];
                                new UserService().addResource(user, resource);

                                TransformThread myThread = new TransformThread(resource, transformPath);
                                Thread thread = new Thread(myThread.beginTransformPdf);
                                thread.Start();
                                Response.Write("<script>alert('上传成功');</script>");
                                Response.Write("<script>window.location.href='self.aspx';</script>");
                                return;
                            }
                            break;
                        default:
                            break;
                    }
                    return;
                }
                if (type == 3) //其他文件
                {
                    dir = Server.MapPath("~/uploaded/");
                    bigFileDir = dir + "media/" + bigFileName;
                    string newName = FileUtil.renameFile(bigFileName, CommonUtil.getGUID());
                    string path = dir + "docs/source/" + newName;
                    //重命名文件
                    File.Move(bigFileDir, path);

                    Hashtable ht = rs.uploadResource(
                                        resourceName,
                                        user,
                                        categoryId,
                                        keywords,
                                        bigFileName,
                                        path,
                                        "",
                                        description,
                                        departmentId,
                                        3
                                       );
                    if ((string)ht["result"] == "0")
                    {
                        //上传失败
                        string message = (string)ht["message"];
                        Response.Write("<script>alert('" + message + "');</script>");
                    }
                    else
                    {
                        //上传成功
                        new UserService().addResource(user, (Resource)ht["resource"]);
                        Response.Write("<script>alert('上传成功');</script>");
                        Response.Write("<script>window.location.href='self.aspx';</script>");
                    }
                    return;
                }
            }

            return;
        }

        [WebMethod]
        public static string analyzeKeywords(string resourceName, string description)
        {
            IList<string> words = new ResourceService().analyzeKeywors(resourceName, description);
            string result = "";
            foreach (string word in words)
            {
                result += word + ",";
            }
            if (result.Length > 0)
                result = result.Substring(0, result.Length - 1);
            return result;
        }


    }

    public class TransformThread
    {
        private Resource resource;
        private string transformPath;
        public TransformThread(Resource resource, string transformPath)
        {
            this.resource = resource;
            this.transformPath = transformPath;
        }
        public void beginTransformWord()
        {
            //转为PDF文件                        
            Transform.WordConvertToPDF(resource.physicalPath, transformPath + ".pdf");
            //转为flash文件
            Transform.PDFConvertToSWF(transformPath + ".pdf", resource.transformPath);
            //得到文档内容
            string content = Transform.Doc2Text(resource.physicalPath);
            //开始建立索引
            SearchUtil.addDocument(
                                    Convert.ToString(resource.id),
                                    resource.resourceName,
                                    resource.description,
                                    content
                                   );
        }
        public void beginTransformPdf()
        {
            //转为flash文件
            Transform.PDFConvertToSWF(resource.physicalPath, resource.transformPath);
            //得到文档内容
            string content = Transform.pdf2txt(resource.physicalPath);
            //开始建立索引
            SearchUtil.addDocument(
                                    Convert.ToString(resource.id),
                                    resource.resourceName,
                                    resource.description,
                                    content
                                   );
        }

    }

}